<?php

class Unit_bind extends CI_Model {

	function __construct() {
		parent::__construct();
	}

	function filter($data) {
		$msg = array();
		if (!array_key_exists('unit_id', $data)) $msg[] = '计费单元必须提供'; 
		if (!array_key_exists('domain_id', $data)) $msg[] = '绑定域名必须提供';
		
		foreach ($data as $k => $v) {
			switch ($k) {
				case 'unit_id':
					if (intval($v) == 0) $msg[] = '计费单元数据错误';
					break;
				case 'domain_id':
					if (count($v) == 0) $msg[] = '域名数据错误';
					break;
			}
		} 
		$status = FALSE;
		if (empty($msg)) {
			$status = TRUE;
		}
		return array('status' => $status, 'msg' => $msg);
	}

	function add($cond) {
		$domain = $cond['domain_id'];
		if (empty($domain)) return;
		$ids = array();
		foreach ($domain as $v) {
			$data['unit_id'] = $cond['unit_id'];
			$data['domain_id'] = $v;
			$data['status'] = 1;
			if (!$this->exist($data)) {
				$data['created_at'] = date('Y-m-d h:i:s', mktime());
				$data['updated_at'] = date('Y-m-d h:i:s', mktime());
				$this->db->insert('unit_bind', $data);
				$ids[] = $this->db->insert_id();
				$this->db->where('id', $v);
				$this->db->update('domain', array('bind_flag' => 1));
			}
		}
		return $ids;
	}

	function exist($cond) {
		$this->db->where($cond);
		$query = $this->db->get('unit_bind');
		if ($query->num_rows() >= 1) return TRUE;
		return FALSE;	
	}

	function del($cond) {
		$data = array('status' => 0);
		$data['updated_at'] = date('Y-m-d h:i:s', mktime());
		$this->db->where($cond);
		$this->db->update('unit_bind', $data); 
		$this->db->where('id', $cond['domain_id']);
		$this->db->update('domain', array('bind_flag' => 0));
	}

	function bdomain($id) {
		$cond['unit_id'] = $id;
		$cond['status'] = 1;
		$this->db->where($cond);
		$query = $this->db->get('unit_bind');
		return $query->result_array();
	}

}
